﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities.IRepository;
using BLToolkit.Data;
using BLToolkit.Data.Linq;
using Entities;

namespace DAL
{
  public  class ChiTietHoaDonRepository:IChiTietHoaDonRepository
    {
      public DbManager db = new DbManager("QuanLyBilliards");
        public List<ChiTietHoaDon> getAll()
        {
            return db.GetTable<ChiTietHoaDon>().ToList();
        }

      /// <summary>
      /// 
      /// </summary>
      /// <returns></returns>
        public List<DoiTuongThongKe> getDoiTuongThongKe()
        {
            List<DoiTuongThongKe> dstk = new List<DoiTuongThongKe>();
            //List<IGrouping<string, ChiTietHoaDon>> ds = getAll().GroupBy(x => x.HangHoa).ToList();
            var dshh = from k in getAll() group k by k.HangHoa;
            DoiTuongThongKe dt;
            foreach (var item in dshh)
            {
                dt = new DoiTuongThongKe();
                dt.MaHH = item.Key;
                dt.SoLuong = item.Sum(x => x.SoLuong);
                dt.Tien = item.Sum(x => x.TongTienSauGiamGia);
                dstk.Add(dt);
                
            }
            return dstk;
           
        }
        public IQueryable<ChiTietHoaDon> getByMaHD(string mahd)
        {
            return db.GetTable<ChiTietHoaDon>().Where(cthd => cthd.MaHD == mahd);
        }


        public bool DeleteByMaHD(string mahd)
        {
            IQueryable<ChiTietHoaDon> list = getByMaHD(mahd);
            foreach (var item in list)
            {
                if (!Delete(item))
                    return false;
            }
            return true;
        }


        public bool Delete(ChiTietHoaDon cthd)
        {
           return db.Delete(cthd)>0;
        }

    }
}
